package com.fy.customview.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.fy.customview.R;
import com.fy.customview.utils.BitmapUtil;

import java.math.BigDecimal;

/**
 * 尝试通过自定义View实现动画
 */
public class BitmapView extends View {

    private final String TAG = "BitmapView";

    private int[] defaultImgIds = new int[]{R.mipmap.widget_keyboard_play_2_02, R.mipmap.widget_keyboard_play_2_03,
            R.mipmap.widget_keyboard_play_2_04, R.mipmap.widget_keyboard_play_2_05, R.mipmap.widget_keyboard_play_2_06,
            /*R.mipmap.widget_keyboard_play_2_07, R.mipmap.widget_keyboard_play_2_08, R.mipmap.widget_keyboard_play_2_09,*/
            R.mipmap.widget_keyboard_play_1_1, R.mipmap.widget_keyboard_play_1_2,
            R.mipmap.widget_keyboard_play_1_3, R.mipmap.widget_keyboard_play_1_4, R.mipmap.widget_keyboard_play_1_5,
            R.mipmap.widget_keyboard_play_1_6};

    private Bitmap[] defaultBitmap = new Bitmap[defaultImgIds.length];

    private int bitmapIndex = -1;

    private Bitmap cai_gou;

    private Paint paint;

    private int width, height;

    public BitmapView(Context context) {
        this(context, null);
    }

    public BitmapView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BitmapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        loadRes();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        Log.d(TAG, "onMeasure->widthMode:" + widthMode + ",measureWidth:" + measureWidth);
        Log.d(TAG, "onMeasure->heightMode:" + heightMode + ",measureHeight:" + measureHeight);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        Log.d(TAG, "onSizeChanged->w:" + w + ",h:" + h + ",oldw:" + oldw + ",oldh:" + oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        Log.d(TAG, "onDraw->isLoadResSuccess:" + isLoadResSuccess);
        if (isLoadResSuccess) {
//            drawFrameBitmap(canvas);
            drawCroppedBitmap(canvas);
        }
    }

    private void drawCroppedBitmap(Canvas canvas) {
        Bitmap bitmap = null;
        float top = 0;
        Matrix matrix = new Matrix();

        Log.d(TAG, "drawCroppedBitmap->cutRate:" + cutRate.floatValue());
        Log.d(TAG, "drawCroppedBitmap->cutRate:" + cutRate);
        matrix.postScale(cutRate.floatValue(),1f);
        if (cutRate.floatValue() <= 1 && cutRate.floatValue() > 0) {
            top = cai_gou.getHeight() * (1 - cutRate.floatValue());
            bitmap = Bitmap.createBitmap(cai_gou, 0, (int) (cai_gou.getHeight() * (1 - cutRate.floatValue())), cai_gou.getWidth(),
                    (int) (cai_gou.getHeight() * cutRate.floatValue()),matrix,true);
        } else if (cutRate.floatValue() > 1 && cutRate.floatValue() < 2) {
            top = 0;
            bitmap = Bitmap.createBitmap(cai_gou, 0, 0, cai_gou.getWidth(), (int) (cai_gou.getHeight() * (2 - cutRate.floatValue())));
        } else if (cutRate.floatValue() > 2 && cutRate.floatValue() <= 3) {
            top = 0;
            bitmap = Bitmap.createBitmap(cai_gou, 0, 0, cai_gou.getWidth(), (int) (cai_gou.getHeight() * (cutRate.floatValue() - 2)));
        } else if (cutRate.floatValue() > 3 && cutRate.floatValue() < 4) {
            top = cai_gou.getHeight() * (cutRate.floatValue() - 3);
            bitmap = Bitmap.createBitmap(cai_gou, 0, (int) (cai_gou.getHeight() * (cutRate.floatValue() - 3)), cai_gou.getWidth(),
                    (int) (cai_gou.getHeight() * (4 - cutRate.floatValue())));
        }
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, 0, top, paint);
        }

    }

    private BigDecimal cutRate = BigDecimal.valueOf(0);

    public void startCroppedAnimation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    cutRate = cutRate.add(BigDecimal.valueOf(0.1f));
                    postInvalidate();
                    SystemClock.sleep(40);
                }
            }
        }).start();
    }

    private void drawFrameBitmap(Canvas canvas) {
        //按指定图片索引画图
        if (bitmapIndex >= 0 && bitmapIndex < defaultBitmap.length) {
            canvas.drawBitmap(defaultBitmap[bitmapIndex], 0, 0, paint);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        Log.d(TAG, "onWindowFocusChanged->hasWindowFocus:" + hasWindowFocus);
    }

    /**
     * 按照帧动画的原理，定时更换设定好的图片
     */
    public void startFrameAnimation() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < defaultBitmap.length; i++) {
                    bitmapIndex = i;
                    postInvalidate();//这里试过调用invalidate()方法，居然也没有报错
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //资源加载是否完成
    private boolean isLoadResSuccess;

    private void loadRes() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "loadRes->run->start time:" + System.currentTimeMillis());
                //默认宽高100dp
                width = getResources().getDimensionPixelSize(R.dimen.dp_100);
                height = getResources().getDimensionPixelSize(R.dimen.dp_100);
                for (int i = 0; i < defaultImgIds.length; i++) {
                    defaultBitmap[i] = BitmapFactory.decodeResource(getResources(), defaultImgIds[i]);
                }
//                cai_gou = BitmapFactory.decodeResource(getResources(),R.mipmap.cai_gou);
                cai_gou = BitmapUtil.createBitmap(getContext(), R.mipmap.cai_gou, width, height);
                isLoadResSuccess = true;
                Log.d(TAG, "loadRes->run->end time:" + System.currentTimeMillis());
            }
        }).start();
    }
}
